﻿using KL.Standard.Domain.Repositories;
using KL.Standard.Model.Infrastructure;
using Microsoft.AspNetCore.Mvc;
using Microsoft.AspNetCore.Mvc.Filters;

namespace EagCentralPlatform.Net8.Filter
{
    /// <summary>
    /// 检查controller 的action 是否被禁用
    /// </summary>
    public class ForbidFilterAttribute: ActionFilterAttribute
    {

        private readonly string uID;
        

        public ForbidFilterAttribute()
        {
            this.uID = System.Guid.NewGuid().ToString();

        }
        
        public override void OnActionExecuting(ActionExecutingContext actionContext)
        {
            string controllerName = actionContext.RouteData.Values["Controller"].ToString();
            string actionName = actionContext.RouteData.Values["Action"].ToString();
            var repository = actionContext.HttpContext.RequestServices.GetService(typeof(ISysRepository)) as  ISysRepository;
            var log =
                actionContext.HttpContext.RequestServices.GetService(typeof(ILogger<ForbidFilterAttribute>)) as
                    ILogger<ForbidFilterAttribute>;
            if (repository != null)
            {
                var key = (controllerName + '.' + actionName).ToLower();
                if(repository.Forbid4ctrAction(key))
                {
                    log.LogInformation("{0} 被禁用执行",key);
                    var json = new OkObjectResult(new BaseResult<string>()
                        {
                            success = false,
                            error = $"该功能已经被禁用，请在EAG中台中操作"
                        }
                    );
                    actionContext.Result = json;
                }
            }
        }
    }
}